// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
	const openId = cloud.getWXContext().OPENID
	const {
		_id,
		type
	} = event
	
	let collectionName = ''
	switch (type) {
		case 0:
			collectionName = 'topics_info'
			break
		case 1:
			collectionName = 'idles_info'
			break
		case 2:
			collectionName = 'runErrands_info'
			break
		case 3:
			collectionName = 'leases_info'
			break
	}
	const result = await db.collection(collectionName).where({
		_id,
		likesMenberGroup: _.all([openId])
	}).count()

	if (result.total) {
		return await db.collection(collectionName).doc(_id).update({
			data: {
				likes: _.inc(-1),
				likesMenberGroup: _.pull(openId),
			},
		})
	} else {
		return await db.collection(collectionName).doc(_id).update({
			data: {
				likes: _.inc(1),
				likesMenberGroup: _.push([openId]),
			},
		})
	}
}
